<script setup lang="ts">

import { useRoute } from 'vue-router';
import { onMounted, reactive } from 'vue';
import { PageEntity } from '@/entitu/page.entity';
import { postAction, uploadAction } from '@/api/common';
import { getOpenCoursePageApi, setClassHoursApi } from '@/api/course';
import { FilterEnum } from '@/common/filter.enum';
import { StatusEnum } from '@/common/status.enum';
import { showToast } from 'vant';
import { getSourceUrl, uploadUrl } from '@/utils/request';

const route = useRoute();
const state = reactive({
  courseId: [],
  openCourseList: [],
  pageInfo: new PageEntity(),
  studentName: '',
  showClassHourModal: false,
  type: null,
  infoId: '',
  classHours: null,
  showStudentName: '',
  fileList: [],
  fileIdMap: {}
})
const getOpenCourseList = () => {
  state.pageInfo.filters.courseId = {
    value: state.courseId,
    matchMode: FilterEnum.LIKE
  };
  if (state.studentName) {
    state.pageInfo.filters.studentName = {
      value: state.studentName,
      matchMode: FilterEnum.LIKE
    }
  } else {
    delete state.pageInfo.filters.studentName;
  }
  postAction(getOpenCoursePageApi, state.pageInfo).then(res => {
    if (res.code === StatusEnum.SUCCESS) {
      state.openCourseList = res.data.data;
    }
  });
};
const clickShowClassHour = (data: string, type: number) => {
  state.showClassHourModal = true;
  state.type = type;
  state.infoId = data.id;
  state.classHours = null;
  state.showStudentName = data.studentName;
  state.fileIdMap = [];
  state.fileList = [];
};
const afterReadImg = file => {
  const formData = new FormData();
  formData.append('file', file.file);
  formData.append("moduleName", 'workImg');
  uploadAction(uploadUrl, formData).then(res => {
    if (res.code === StatusEnum.SUCCESS) {
      // 为了正常显示，删除最后一个
      state.fileList.splice(-1, 1);
      state.fileIdMap[res.data.fileNewName] = res.data.id;
      state.fileList.push({
        url: getSourceUrl(res.data)
      });
    }
  });
};
const getFileName = (url) => {
  return url.split('/').pop();
}
const clickConfirm = () => {
  const imgIds = [];
  state.fileList.map(item => {
    if (state.fileIdMap[getFileName(item.url)]) {
      imgIds.push(state.fileIdMap[getFileName(item.url)]);
    }
  });
  if (!state.classHours) {
    showToast('请输入课时');
    return;
  }
  postAction(setClassHoursApi, {
    id: state.infoId,
    classHours: state.classHours,
    type: state.type,
    workImgIdList: imgIds
  }).then(res => {
    if (res.code === StatusEnum.SUCCESS) {
      getOpenCourseList();
      state.showClassHourModal = false;
      setTimeout(() => {
        showToast('操作成功');
      }, 1000);
    }
  });
}
onMounted(() => {
  state.courseId = route.params.id;
  getOpenCourseList();
});
</script>

<template>
  <div class="set-class-hours-container h100">
    <div class="search-bar">
      <van-search v-model="state.studentName" placeholder="请输入学生姓名" @update:model-value="getOpenCourseList" />
    </div>
    <div v-if="state.openCourseList.length" class="open-course-list">
      <div class="open-item" v-for="item in state.openCourseList" :key="item.id">
        <div class="name item">{{item.studentName}}</div>
        <div class="remain-hour">剩余课时：{{item.classHours}}</div>
        <div class="operate-btn">
          <van-button plain hairline size="small" @click="clickShowClassHour(item, 1)">添加课时</van-button>
          <van-button plain hairline type="warning" size="small" @click="clickShowClassHour(item, 2)">扣除课时</van-button>
        </div>
      </div>
    </div>
    <NoData v-else />
    <van-popup
        v-model:show="state.showClassHourModal"
        round
        position="bottom"
        :safe-area-inset-bottom="true"
    >
      <div class="title">{{state.showStudentName}}-{{state.type === 1 ? '添加课时' : '扣除课时'}}</div>
      <van-field v-model="state.classHours" required type="digit" label="课时" placeholder="请输入课时" />
      <van-uploader v-model="state.fileList" multiple accept=".jpg,.png,.jpeg"
                    :max-count="5" :after-read="afterReadImg" />
      <div class="footer">
        <div class="cancel btn" @click="state.showClassHourModal = false">取消</div>
        <div class="confirm btn" @click="clickConfirm">确定</div>
      </div>
    </van-popup>
  </div>
</template>

<style scoped lang="scss">
  .set-class-hours-container{
    display: flex;
    flex-direction: column;
    .search-bar{
      height: 100px;
    }
    .open-course-list{
      flex: 1;
      overflow-y: auto;
      .open-item{
        padding: 20px;
        background: #fff;
        margin-bottom: 10px;
        border-radius: 10px;
        .item{
          margin-bottom: 30px;
        }
        .operate-btn{
          margin-top: 30px;
          display: flex;
          justify-content: space-between;
        }
      }
    }
  }
  .title{
    font-weight: 700;
    text-align: center;
    padding: 20px;
  }
  .footer{
    display: flex;
    justify-content: space-between;
    border-top: 1px solid #f2f2f2;
    .confirm{
      color: #1989fa;
      border-left: 1px solid #f2f2f2;
    }
    .btn{
      flex: 1;
      text-align: center;
      padding: 40px;
    }
  }
</style>
